<?php
/**
 * Created by PhpStorm.
 * User: wincol
 * Date: 2018/3/18
 * Time: 15:22
 */

namespace App\Http\Controllers;


use ElfSundae\BearyChat\Laravel\BearyChat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HooksController extends Controller
{
    public function index(Request $request)
    {
        if ($string = $request->getContent()) {
            $str_arr = json_decode($string, true);
            if (!isset($str_arr['password'])&&$str_arr['password'] != 'wellpush') {
                return;

            }
            $orders = [
                'cd /home/wwwroot/api',
                'git remote update -p',
                'git checkout -f origin/master',
                'git submodule update --init',
                'php /home/wwwroot/api/artisan laravels reload'
            ];

            $this->execOrder($orders, '/home/wwwroot/api','dushuba');
        }

    }
    public function dushubaWeb(Request $request){
        $json = $request->getContent();
        if($json){
            $json = json_decode($json, true);
            if(isset($json['commits'])&&$json['password'] == 'dushubahook'){
                foreach ($json['commits'] as $commit){
                    $str = $commit['message'];

                    if(mb_substr($str,-5,5) == '_push'){
                        $str = mb_substr($str, 0 ,mb_strlen($str)-5);
                        BearyChat::client('dushuba')->send($str);
                    }
                }
            }
        }
        echo 'success';
    }
    /**
     * 执行order，webhook
     * @param array $orders
     * @param $root_path
     * @param $program
     */
    protected function execOrder(array $orders, $root_path, $program){
        shell_exec(implode(' && ', $orders));
        $str = exec('cd '.$root_path.' && git log -1 --pretty=format:"%s"');
        if(mb_substr($str,-5,5) == '_push'){
            $str = mb_substr($str, 0 ,mb_strlen($str)-5);
            BearyChat::client($program)->send($str);
        }
    }
}